import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:permission_handler/permission_handler.dart';

/*
 * 获取权限组件
 */
class PermissionRequestWidget extends StatefulWidget {
  final Permission permission;
  final List<String> permissionList;
  final bool isCloseApp;
  final String leftButtonText;
  PermissionRequestWidget(
      {Key key,
      @required this.permission,
      @required this.permissionList,
      this.isCloseApp = false,
      this.leftButtonText = '在考虑一下'})
      : super(key: key);

  @override
  _PermissionRequestWidgetState createState() =>
      _PermissionRequestWidgetState();
}

class _PermissionRequestWidgetState extends State<PermissionRequestWidget>
    with WidgetsBindingObserver {
  bool _isGoSetting = false;
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    Future.delayed(Duration.zero, () {
      checkPermisstion();
    });
  }

  //关闭应用
  void exitApp() {
    SystemChannels.platform.invokeMapMethod('SystemNavigator.pop');
  }

  void showPermissionAlert(
      String message, String rightString, Permission permission,
      {bool isSetting = false}) {
    showCupertinoDialog(
        context: context,
        builder: (BuildContext context) {
          return CupertinoAlertDialog(
            title: Text('温馨提示'),
            content: Container(
              padding: EdgeInsets.all(12),
              child: Text(message),
            ),
            actions: [
              CupertinoDialogAction(
                child: Text(widget.leftButtonText),
                onPressed: () {
                  if (widget.isCloseApp) {
                    exitApp();
                  } else {
                    Navigator.of(context).pop(false);
                  }
                },
              ),
              CupertinoDialogAction(
                child: Text(rightString),
                onPressed: () {
                  Navigator.of(context);
                  if (isSetting) {
                    this._isGoSetting = true;
                    openAppSettings();
                    return;
                  }
                  //申请权限
                  requestPermission(permission);
                },
              ),
            ],
          );
        });
  }

  void requestPermission(Permission permission) async {
    PermissionStatus status = await permission.request();
    checkPermisstion(status: status);
  }

  void checkPermisstion({PermissionStatus status}) async {
    //权限
    Permission permission = widget.permission;

    if (status == null) {
      status = await permission.status;
    }
    //权限状态
    if (status.isUndetermined) {
      //第一次申请
      showPermissionAlert(widget.permissionList[0], '同意', permission);
    } else if (status.isDenied) {
      //用户申请第一次拒绝
      if (Platform.isIOS) {
        showPermissionAlert(widget.permissionList[2], '去设置中心', permission,
            isSetting: true);
        return;
      }
      showPermissionAlert(widget.permissionList[1], '重试', permission);
    } else if (status.isPermanentlyDenied) {
      //第二次申请用户拒绝
      showPermissionAlert(widget.permissionList[2], '去设置中心', permission,
          isSetting: true);
    } else {
      // 通过
      Navigator.of(context).pop(true);
    }
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    //从后台进去前台
    if (state == AppLifecycleState.resumed && this._isGoSetting) {
      checkPermisstion();
    }
  }

  @override
  void dispose() {
    super.dispose();
    WidgetsBinding.instance.removeObserver(this);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.transparent,
    );
  }
}
